{% extends "base.html" %}

{% block title %}鲍鱼信息查询{% endblock %}

{% block content %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>跑鱼数据分析 - 训练</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .form-group {
            margin-bottom: 15px;
        }
        .dialog-container {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .dialog-content {
            background-color: white;
            padding: 20px;
            border-radius: 5px;
            width: 50%;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">跑鱼数据分析</a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <li class="nav-item"><a class="nav-link" href="/">主页</a></li>
                    <li class="nav-item"><a class="nav-link" href="/search">查询</a></li>
                    <li class="nav-item"><a class="nav-link" href="/predict">预测</a></li>
                    <li class="nav-item"><a class="nav-link active" href="/train">训练</a></li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item"><a class="nav-link" href="/logout">退出</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <h2>训练功能实现</h2>

        <div class="row">
            <div class="col-md-6">
                <button id="addDataBtn" class="btn btn-primary">新增数据</button>
                <button id="batchImportBtn" class="btn btn-success">批量导入</button>

                <div class="mt-3">
                    <table class="table table-bordered" id="dataTable">
                        <thead>
                            <tr>
                                <th>编号</th>
                                <th>性别</th>
                                <th>长度</th>
                                <th>直径</th>
                                <th>高度</th>
                                <th>总宽</th>
                                <th>剥皮宽度</th>
                                <th>内脏高度</th>
                                <th>贝壳宽度</th>
                                <th>年龄</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                    <!-- 在分页控件部分修改为以下代码 -->
<div class="pagination d-flex align-items-center">
    <button class="btn btn-sm btn-outline-primary prev-page me-2">上一页</button>

    <div class="input-group me-2" style="width: 100px;">
        <input type="number" class="form-control form-control-sm page-input"
               min="1" value="1">
        <span class="input-group-text">/ <span class="total-pages">1</span></span>
    </div>

    <button class="btn btn-sm btn-outline-primary next-page me-2">下一页</button>

    <select class="form-select form-select-sm per-page-select" style="width: 80px;">
        <option value="10">10条</option>
        <option value="20">20条</option>
        <option value="50">50条</option>
        <option value="100">100条</option>
    </select>

    <span class="ms-2 page-info">
        共 <span class="total-items">0</span> 条
    </span>
</div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5>模型信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="form-group">
                            <label>模型:</label>
                            <select id="modelSelect" class="form-select">
                                <option value="LR">线性回归 (LR)</option>
                                <option value="DT-R">决策树回归 (DT-R)</option>
                                <option value="RF-R">随机森林回归 (RF-R)</option>
                            </select>
                        </div>
                        <button id="trainBtn" class="btn btn-warning">重新训练</button>

                        <div class="mt-3">
                            <p><strong>预测方法:</strong> <span id="predictMethod">LR</span></p>
                            <p><strong>平均绝对误差(MAE):</strong> <span id="mae">-</span></p>
                            <p><strong>均方误差(MSE):</strong> <span id="mse">-</span></p>
                            <p><strong>平方根均方误差(RMSE):</strong> <span id="rmse">-</span></p>
                            <p><strong>决定系数(R-squared):</strong> <span id="r2">-</span></p>
                            <p><strong>训练数据集大小:</strong> <span id="trainSize">-</span></p>
                            <p><strong>测试数据集大小:</strong> <span id="testSize">-</span></p>
                            <p><strong>训练时间:</strong> <span id="trainTime">-</span></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 新增数据对话框 -->
    <div id="addDataDialog" class="dialog-container">
        <div class="dialog-content">
            <h4>新增数据</h4>
            <form id="addDataForm">
                <div class="form-group">
                    <label>性别:</label>
                    <select class="form-select" name="sex" required>
                        <option value="1">雄性</option>
                        <option value="0">雌性</option>
                        <option value="-1">未知</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>长度:</label>
                    <input type="number" step="0.001" class="form-control" name="length" required>
                </div>
                <div class="form-group">
                    <label>直径:</label>
                    <input type="number" step="0.001" class="form-control" name="diameter" required>
                </div>
                <div class="form-group">
                    <label>高度:</label>
                    <input type="number" step="0.001" class="form-control" name="height" required>
                </div>
                <div class="form-group">
                    <label>总宽:</label>
                    <input type="number" step="0.001" class="form-control" name="whole_weight" required>
                </div>
                <div class="form-group">
                    <label>剥皮宽度:</label>
                    <input type="number" step="0.001" class="form-control" name="shucked_weight" required>
                </div>
                <div class="form-group">
                    <label>内脏高度:</label>
                    <input type="number" step="0.001" class="form-control" name="viscera_weight" required>
                </div>
                <div class="form-group">
                    <label>贝壳宽度:</label>
                    <input type="number" step="0.001" class="form-control" name="shell_weight" required>
                </div>
                <div class="form-group">
                    <label>年龄:</label>
                    <input type="number" class="form-control" name="rings" required>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">提交</button>
                    <button type="button" class="btn btn-secondary" onclick="closeDialog('addDataDialog')">取消</button>
                </div>
            </form>
        </div>
    </div>
    <!-- 新增编辑数据对话框 -->
<div id="editDataDialog" class="dialog-container">
    <div class="dialog-content">
        <h4>编辑数据</h4>
        <form id="editDataForm">
            <input type="hidden" name="id">
            <div class="form-group">
                <label>性别:</label>
                <select class="form-select" name="sex" required>
                    <option value="1">雄性</option>
                    <option value="0">雌性</option>
                    <option value="-1">未知</option>
                </select>
            </div>
            <div class="form-group">
                <label>长度:</label>
                <input type="number" step="0.001" class="form-control" name="length" required>
            </div>
            <div class="form-group">
                <label>直径:</label>
                <input type="number" step="0.001" class="form-control" name="diameter" required>
            </div>
            <div class="form-group">
                <label>高度:</label>
                <input type="number" step="0.001" class="form-control" name="height" required>
            </div>
            <div class="form-group">
                <label>总宽:</label>
                <input type="number" step="0.001" class="form-control" name="whole_weight" required>
            </div>
            <div class="form-group">
                <label>剥皮宽度:</label>
                <input type="number" step="0.001" class="form-control" name="shucked_weight" required>
            </div>
            <div class="form-group">
                <label>内脏高度:</label>
                <input type="number" step="0.001" class="form-control" name="viscera_weight" required>
            </div>
            <div class="form-group">
                <label>贝壳宽度:</label>
                <input type="number" step="0.001" class="form-control" name="shell_weight" required>
            </div>
            <div class="form-group">
                <label>年龄:</label>
                <input type="number" class="form-control" name="rings" required>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-secondary" onclick="closeDialog('editDataDialog')">取消</button>
            </div>
        </form>
    </div>
</div>
    <!-- 批量导入对话框 -->
    <div id="batchImportDialog" class="dialog-container">
        <div class="dialog-content">
            <h4>批量导入CSV文件</h4>
            <form id="batchImportForm" enctype="multipart/form-data">
                <div class="form-group">
                    <label>选择CSV文件:</label>
                    <input type="file" class="form-control" name="csvFile" accept=".csv" required>
                    <small class="form-text text-muted">CSV格式: id,sex,length,diameter,height,whole_weight,shucked_weight,viscera_weight,shell_weight,rings</small>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">导入</button>
                    <button type="button" class="btn btn-secondary" onclick="closeDialog('batchImportDialog')">取消</button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 对话框控制函数
        function showDialog(dialogId) {
            document.getElementById(dialogId).style.display = 'flex';
        }

        function closeDialog(dialogId) {
            document.getElementById(dialogId).style.display = 'none';
        }

        // 按钮事件监听
        document.getElementById('addDataBtn').addEventListener('click', function() {
            showDialog('addDataDialog');
        });

        document.getElementById('batchImportBtn').addEventListener('click', function() {
            showDialog('batchImportDialog');
        });

        // 表单提交处理
        {#document.getElementById('addDataForm').addEventListener('submit', function(e) {#}
        {#    e.preventDefault();#}
        {#    const formData = new FormData(this);#}
        {##}
        {#    fetch('/api/train/add_data', {#}
        {#        method: 'POST',#}
        {#        body: formData#}
        {#    })#}
        {#    .then(response => response.json())#}
        {#    .then(data => {#}
        {#        if(data.success) {#}
        {#            alert('数据添加成功');#}
        {#            closeDialog('addDataDialog');#}
        {#            loadData(); // 重新加载数据#}
        {#        } else {#}
        {#            alert('添加失败: ' + data.message);#}
        {#        }#}
        {#    })#}
        {#    .catch(error => {#}
        {#        console.error('Error:', error);#}
        {#        alert('发生错误');#}
        {#    });#}
        {# );#}

        document.getElementById('batchImportForm').addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);

            fetch('/api/train/batch_import', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if(data.success) {
                    alert(`成功导入 ${data.count} 条数据`);
                    closeDialog('batchImportDialog');
                    loadData(); // 重新加载数据
                } else {
                    alert('导入失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误');
            });
        });

        // 训练按钮事件
        document.getElementById('trainBtn').addEventListener('click', function() {
            const modelType = document.getElementById('modelSelect').value;

            fetch('/api/train/retrain', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ model_type: modelType })
            })
            .then(response => response.json())
            .then(data => {
                if(data.success) {
                    // 更新模型信息
                    document.getElementById('predictMethod').textContent = modelType;
                    document.getElementById('mae').textContent = data.mae;
                    document.getElementById('mse').textContent = data.mse;
                    document.getElementById('rmse').textContent = data.rmse;
                    document.getElementById('r2').textContent = data.r2;
                    document.getElementById('trainSize').textContent = data.train_size + '条';
                    document.getElementById('testSize').textContent = data.test_size + '条';
                    document.getElementById('trainTime').textContent = data.train_time + '秒';

                    alert('模型重新训练成功');
                } else {
                    alert('训练失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误');
            });
        });

        // 加载数据函数
        // 修改loadData函数
// 修改loadData函数
function loadData(page = 1) {
    const perPage = parseInt(document.querySelector('.per-page-select').value);

    fetch(`/api/train/get_data?page=${page}&per_page=${perPage}`)
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        const tbody = document.querySelector('#dataTable tbody');
        tbody.innerHTML = '';

        // 确保data.records存在且是数组
        const records = data.records || [];

        if (records.length === 0) {
            const tr = document.createElement('tr');
            tr.innerHTML = '<td colspan="11" class="text-center">暂无数据</td>';
            tbody.appendChild(tr);
        } else {
            records.forEach(record => {
                const tr = document.createElement('tr');
                tr.innerHTML = `
                    <td>${record.id}</td>
                    <td>${record.sex}</td>
                    <td>${record.length}</td>
                    <td>${record.diameter}</td>
                    <td>${record.height}</td>
                    <td>${record.whole_weight}</td>
                    <td>${record.shucked_weight}</td>
                    <td>${record.viscera_weight}</td>
                    <td>${record.shell_weight}</td>
                    <td>${record.rings}</td>
                    <td>
                        <button class="btn btn-sm btn-danger delete-btn me-1" data-id="${record.id}">删除</button>
                        <button class="btn btn-sm btn-info edit-btn" data-id="${record.id}">编辑</button>
                    </td>
                `;
                tbody.appendChild(tr);
            });
        }

        // 更新分页信息
        if (data.success) {
            document.querySelector('.page-input').value = data.current_page;
            document.querySelector('.page-input').max = data.total_pages;
            document.querySelector('.total-pages').textContent = data.total_pages;
            document.querySelector('.total-items').textContent = data.total_items;

            // 禁用/启用分页按钮
            document.querySelector('.prev-page').disabled = data.current_page <= 1;
            document.querySelector('.next-page').disabled = data.current_page >= data.total_pages;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        const tbody = document.querySelector('#dataTable tbody');
        tbody.innerHTML = '<tr><td colspan="11" class="text-center">加载数据失败</td></tr>';
    });
}

// 添加删除功能
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('delete-btn')) {
        const id = e.target.getAttribute('data-id');
        if (confirm('确定要删除这条记录吗?')) {
            fetch(`/api/train/delete_data/${id}`, {
                method: 'DELETE'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('删除成功');
                    loadData(); // 重新加载当前页数据
                } else {
                    alert('删除失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除时发生错误');
            });
        }
    }
});

// 分页控件事件
document.querySelector('.prev-page').addEventListener('click', function() {
    const currentPage = parseInt(document.querySelector('.page-input').value);
    if (currentPage > 1) {
        loadData(currentPage - 1);
    }
});

document.querySelector('.next-page').addEventListener('click', function() {
    const currentPage = parseInt(document.querySelector('.page-input').value);
    const totalPages = parseInt(document.querySelector('.total-pages').textContent);
    if (currentPage < totalPages) {
        loadData(currentPage + 1);
    }
});

// 页码输入框事件
document.querySelector('.page-input').addEventListener('change', function() {
    const page = parseInt(this.value);
    const totalPages = parseInt(document.querySelector('.total-pages').textContent);
    if (page >= 1 && page <= totalPages) {
        loadData(page);
    } else {
        this.value = 1;
    }
});

// 每页显示数量变化事件
document.querySelector('.per-page-select').addEventListener('change', function() {
    loadData(1); // 切换每页显示数量时回到第一页
});
// 添加编辑按钮事件
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('edit-btn')) {
        const id = e.target.getAttribute('data-id');
        fetch(`/api/train/get_single_data/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                const form = document.getElementById('editDataForm');
                const record = data.record;

                // 填充表单
                form.elements['id'].value = record.id;
                form.elements['sex'].value = record.sex;
                form.elements['length'].value = record.length;
                form.elements['diameter'].value = record.diameter;
                form.elements['height'].value = record.height;
                form.elements['whole_weight'].value = record.whole_weight;
                form.elements['shucked_weight'].value = record.shucked_weight;
                form.elements['viscera_weight'].value = record.viscera_weight;
                form.elements['shell_weight'].value = record.shell_weight;
                form.elements['rings'].value = record.rings;

                showDialog('editDataDialog');
            } else {
                alert('获取数据失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取数据时发生错误');
        });
    }
});

// 编辑表单提交
document.getElementById('editDataForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const formData = new FormData(this);

    fetch('/api/train/update_data', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('更新成功');
            closeDialog('editDataDialog');
            loadData(); // 重新加载当前页数据
        } else {
            alert('更新失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('更新时发生错误');
    });
});
document.getElementById('addDataForm').addEventListener('submit', function(e) {
    e.preventDefault();

    // 收集表单数据
    const formData = new URLSearchParams();
    const formElements = this.elements;

    for (let i = 0; i < formElements.length; i++) {
        const element = formElements[i];
        if (element.name && element.value) {
            formData.append(element.name, element.value);
        }
    }
    console.log(formData);

    // 发送请求
    fetch('/api/train/add_data', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            return response.json().then(err => {
                throw new Error(err.message || '请求失败');
            });
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            alert(`数据添加成功，ID: ${data.id}`);
            closeDialog('addDataDialog');
            // 重置表单
            this.reset();
            // 重新加载数据
            loadData();
        } else {
            alert('添加失败: ' + (data.message || '未知错误'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('发生错误: ' + error.message);
    });
});
// 初始化加载数据
loadData();
    </script>
</body>
</html>
{% endblock %}